<template>
    <inner-layout v-loading="loading">

        <div class="filter-bar clearfix">
            <div class="filter-item">
                <span class="filter-item-title">品种1</span>
                <el-select v-model="apiParams.code1" placeholder="请选择" class="filter-item-select">
                    <el-option
                      v-for="(v, k) in futuresSymbolList"
                      :key="k"
                      :label="k + `_` + v"
                      :value="k">
                    </el-option>
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-item-title">品种2</span>
                <el-select v-model="apiParams.code2" placeholder="请选择" class="filter-item-select">
                    <el-option
                      v-for="(v, k) in futuresSymbolList"
                      :key="k"
                      :label="k + `_` + v"
                      :value="k">
                    </el-option>
                </el-select>
            </div>

            <div class="filter-item">
                <el-button type="primary" plain :disabled="loading" @click="eventAddPriceDiffSymbol">添加价差</el-button>
            </div>


            <div class="filter-item">
                <i class="el-icon-info"></i> 共{{ Object.keys(configFuturesVs).length }}对商品价差数据
            </div>

            <div class="filter-item">
                <el-button :disabled="loading" @click="filterData">刷新</el-button>
            </div>
        </div>
        

        <div class="list-wrap">
            <el-table :data="dataList" stripe style="width:100%">
                <el-table-column
                    prop="symbol"
                    label="代码">
                </el-table-column>

                <el-table-column
                    prop="name"
                    label="名称">
                </el-table-column>
                <el-table-column
                    prop="price1"
                    label="价格1">
                </el-table-column>
                <el-table-column
                    prop="price2"
                    label="价格2">
                </el-table-column>
                <el-table-column
                    prop="priceDiff"
                    label="价差">
                </el-table-column>
                
                <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-popconfirm title="确认要移除吗？" @onConfirm="eventRemovePriceDiffSymbol(scope.row)">
                                <el-button slot="reference" size="mini" icon="el-icon-delete"></el-button>
                            </el-popconfirm>
                            <!-- <el-button size="mini" icon="el-icon-delete" @click="eventRemovePriceDiffSymbol(scope.row)"></el-button> -->
                            <el-button size="mini" icon="el-icon-s-marketing" @click="eventChartPriceDiffSymbol(scope.row)" style="margin-left:5px;"></el-button>
                        </template>
                    </el-table-column>
            </el-table>
        </div>


        <div class="tip-wrap">
            <div><i class="el-icon-info"></i>商品期货数据来源：新浪</div>
            <div class="fr">
                <a href="http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_0" target="_blank">去新浪查看详情&gt;&gt;</a>
            </div>
        </div>
    </inner-layout>
</template>

<script>
import { getSinaQuote, praseSinaJsStr } from '@/api/sina'
import { get10JqkaQuoteLast, prase10JqkaJsStrForV6Time } from '@/api/jqka10'
import { futuresSymbolList } from '@/config'
export default {
	name: 'FuturesVsFutures',
	components: { },
    directives: { },
	mixins: [],
	data() {
		return {
			loading: false,
            futuresSymbolList: {},
            configFuturesVs: {},
			dataList: [],
            apiParams: {
                code1: '',
                code2: ''
            }
		}
	},
	created() {
        this.futuresSymbolList = futuresSymbolList()
        this.configFuturesVs = this.futuresVsConfig()
		this.getPageData()
	},
	methods: {
		getPageData() {
            let that = this

            that.dataList = []
            let _symbols = []
			Object.keys(that.configFuturesVs).forEach(k => {
                let _symbol = k.split('__VS__')
                _symbols.push('nf_' + _symbol[0] + '0')
                _symbols.push('nf_' + _symbol[1] + '0')
            })
            that.getFuturesData(_symbols)

            // Object.keys(that.configFuturesVs).forEach(k => {
            //     that.getFuturesDataFor10Jqka(k)
            // })
		},
        getFuturesDataFor10Jqka(symbol) {
            let that = this
            let _symbol = symbol.split('__VS__')
            get10JqkaQuoteLast(_symbol[0]).then(res => {
                if (res.err_code === 0) {
                    let _price1 = prase10JqkaJsStrForV6Time(_symbol[0], res.data)
                    get10JqkaQuoteLast(_symbol[1]).then(res => {
                        if (res.err_code === 0) {
                            let _price2 = prase10JqkaJsStrForV6Time(_symbol[1], res.data)
                            let _row = {
                                symbol: symbol,
                                name: that.configFuturesVs[symbol],
                                price1: _price1,
                                price2: _price2,
                                priceDiff: _price1 - _price2
                            }
                            that.dataList.push(_row)
                        }
                    })
                }
            })
        },
        getFuturesData(symbol) {
            let that = this

            that.loading = true
            symbol = symbol || []
            if (symbol.length > 0) {
                getSinaQuote(symbol.join(',')).then(res2 => {
                    if (res2.err_code === 0) {
                        let _jsStr = praseSinaJsStr(res2.data) || {}
                        Object.keys(that.configFuturesVs).forEach(k => {
                            let _symbol = k.split('__VS__')
                            let _price1 = _jsStr['nf_'+_symbol[0]+'0'][8] * 1 || 0
                            let _price2 = _jsStr['nf_'+_symbol[1]+'0'][8] * 1 || 0
                            let _row = {
                                symbol: k,
                                name: that.configFuturesVs[k],
                                price1: _price1,
                                price2: _price2,
                                priceDiff: _price1 - _price2
                            }
                            that.dataList.push(_row)
                        })
                        // that.dataList = that.dataList.sort(function(a, b){return b.chgRate - a.chgRate})
                        console.log('getSinaQuote', that.dataList)
                    }
                }).finally(() => {
                    console.info('getSinaQuote--finally() is executing!');
                    that.loading = false
                })
            }
        },
        filterData() {
            this.getPageData()
        },
        eventAddPriceDiffSymbol() {
            if (!this.apiParams.code1 || !this.apiParams.code2) {
                this.$message.error('请选择需要计算价差的商品')
                return
            } else if (this.apiParams.code1 == this.apiParams.code2) {
                this.$message.error('两个商品不能相同')
                return
            }
            this.configFuturesVs[this.apiParams.code1 + '__VS__' + this.apiParams.code2] = this.futuresSymbolList[this.apiParams.code1] + ' VS ' + this.futuresSymbolList[this.apiParams.code2]
            this.configFuturesVs = Object.assign({}, this.configFuturesVs)
            this.futuresVsConfig(this.configFuturesVs)
        },
        eventRemovePriceDiffSymbol(row) {
            console.log('eventRemovePriceDiffSymbol', row)
            let _conf = this.configFuturesVs
            delete _conf[row.symbol]
            this.configFuturesVs = Object.assign({}, _conf)
            this.futuresVsConfig(_conf)

            this.dataList = this.dataList.filter(dataRow => {
                return row.symbol != dataRow.symbol
            })
        },
        eventChartPriceDiffSymbol(row) {
            console.log('eventChartPriceDiffSymbol', row)
            let that = this
            let _symbol = row.symbol.split('__VS__')
            that.$router.push({
                name: 'FuturesVsFuturesHistory',
                query: {
                    code1: _symbol[0],
                    code2: _symbol[1],
                }
            })
        },
        futuresVsConfig(setVal) {
            let _cacheKey = 'futures_vs_futures_symbol'

            if (setVal) {
                localStorage.setItem(_cacheKey, JSON.stringify(setVal))
                return true
            }

            let _conf = localStorage.getItem(_cacheKey)
            if (_conf && _conf != '{}') {
                return JSON.parse(_conf)
            }

            return {
                'SF__VS__SM': '硅铁 VS 锰硅',
                'A__VS__M': '豆一 VS 豆粕',
                'Y__VS__P': '豆油 VS 棕榈油',
                'RB__VS__HC': '螺纹钢 VS 热轧卷板',
                // 'CU__VS__BC': '沪铜 VS 国际铜',
                // 'SA__VS__FG': '纯碱 VS 玻璃',
            }
        }
	}
}
</script>

<style lang="scss" scoped>
    .list-wrap {
        margin-top: 30px;
    }
    .tip-wrap {
        padding: 30px 0;
        font-size: 13px;
        line-height: 26px;
    }
    .filter-item {
        .filter-item-title {
            margin-right: 5px;
        }
        .filter-item-select {
            width: 120px;
        }
    }
    .charts-wrap {
        width: 100%;
        height: 350px;
        #chartObj {
            width: 100%;
            height: 350px;
        }
    }
</style>
